package com.frejoys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.common.appversion.AppVersionAddDto;
import com.frejoys.common.dto.common.appversion.AppVersionInfoDto;
import com.frejoys.common.dto.common.appversion.AppVersionListDto;
import com.frejoys.common.dto.common.IdDto;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.dao.entity.AppVersion;
import com.frejoys.dao.mapper.AppVersionMapper;
import com.frejoys.service.AppVersionService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

// app升级版本
@Service
@RequiredArgsConstructor
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService {

    @Override
    @CacheEvict(cacheNames = "appVersion", allEntries = true)
    public boolean addInfo(AppVersionAddDto dto) {
        return save(new AppVersion(){{
            setVersion(dto.getVersion());
            setAddress(dto.getAddress());
            setType(dto.getType());
            setUpgradeType(dto.getUpgradeType());
            setUpgradeTime(TimeUtil.unixTime(dto.getUpgradeTime()));
            setCreateTime(TimeUtil.unixTime());
        }});
    }

    @Override
    @CacheEvict(cacheNames = "appVersion", allEntries = true)
    public boolean delInfo(IdDto dto) {
        LambdaQueryWrapper<AppVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppVersion::getId, dto.getId());
        return remove(wrapper);
    }

    @Override
    @Cacheable(cacheNames = "appVersion", key = "#dto.type", unless = "#result == null")
    public AppVersion getLastInfo(AppVersionInfoDto dto) {
        LambdaQueryWrapper<AppVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppVersion::getType, dto.getType());
        wrapper.orderByDesc(AppVersion::getId);
        return getOnly(wrapper);
    }

    @Override
    public List<AppVersion> listInfo(AppVersionListDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);

        LambdaQueryWrapper<AppVersion> wrapper = new LambdaQueryWrapper<>();

        if (dto.getType() != null) {
            wrapper.eq(AppVersion::getType, dto.getType());
        }

        if (dto.getUpgradeType() != null) {
            wrapper.eq(AppVersion::getUpgradeType, dto.getUpgradeType());
        }

        if (dto.getVersion() != null) {
            wrapper.eq(AppVersion::getVersion, dto.getVersion());
        }

        wrapper.orderByDesc(AppVersion::getId);

        return baseMapper.selectPage(page, wrapper).getRecords();
    }

}